package com.gopay.checkorder.service.impl.bcdl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;



import com.gopay.common.cipher.utils.LoggerMaskUtils;
import com.gopay.gass.service.GassPayRemoteService;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.gopay.checkorder.dao.BcdlQueryBalanceDAO;
import com.gopay.checkorder.dao.BisBankOrderQueryDAO;
import com.gopay.checkorder.manager.BankOrderManager;
import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.BcdlOrderSendBankService;
import com.gopay.checkorder.service.BcdlOrderService;
import com.gopay.checkorder.service.sentinel.BcdlOrderSentinel;
import com.gopay.common.constants.bank.BCDLConstants;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BankOrderStatus;
import com.gopay.common.constants.bank.BankOrderType;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.cps.manager.order.CpsGeneralMainOrderQueryManager;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BcdlQueryBalance;
import com.gopay.common.domain.bank.BcdlResult;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.exception.GopayException;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.HttpTransport;
import com.gopay.common.util.StringTools;
import com.gopay.common.util.spring.SpringContextUtil;
@Service("bcdlOrderService")
public class BcdlOrderServiceImpl implements BcdlOrderService{
	private final static Logger logger = LoggerFactory.getLogger(BcdlOrderServiceImpl.class);


	//modified by zyt，单独摘出一个service，针对银企直联处理
	/*@Resource(name = "bankOrderService")
	private BankOrderService bankOrderService;*/
	@Resource(name = "bcdlBankOrderService")
	private BankOrderService bcdlBankOrderService;

	private int MAX_SIZE=100;
	
    @Resource(name = "cpsGeneralMainOrderQueryManager")
    protected CpsGeneralMainOrderQueryManager mainOrderQuery;
    @Resource(name = "bankOrderManager")
    protected BankOrderManager bankOrderManager;
    
    @Resource(name = "bisBankOrderQueryDAO")
    private BisBankOrderQueryDAO bisBankOrderQueryDAO;
    @Resource(name = "bcdlQueryBalanceDAO")
    private BcdlQueryBalanceDAO bcdlQueryBalanceDAO;
    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;
    @Resource(name = "bcdlConfig")
	private Map<String, String> bcdlConfig;
	@Resource(name = "gassPayService")
	private GassPayRemoteService gassPayService;
    
	public void process(String bank, String notifyUrl, BcdlOrderSentinel sentinel) {
		if (sentinel.isFuse()) {
			logger.error("bcdl_" + bank + ",暂停付款任务");
			
			oneTestOrder(bank,sentinel);
			return;
		} 

		// modified by zyt,2017-10-10,抽出公用的合法时间校验到bankOrderManager中，时间校验前置，防止查询db后又被时间拦截，浪费db与服务的io
		if(!bankOrderManager.isLegalTime(bank)){
			return;
		}

		StopWatch sw = new StopWatch();
		sw.start();
		// List<BankOrder> sendOrders = getSendBankOrder(bank);
		List<String> sendOrders = getSendBankOrder(bank);
		
		sw.split();
		logger.error(bank + "-----------getSendBankOrder耗时=" + sw.getSplitTime());
		logger.error("-----------" + bank + "发往银行记录总数=" + sendOrders.size());

		List<BankOrder> checkOrders = getCheckOrder(bank, (MAX_SIZE - sendOrders.size()));
		sw.split();
		logger.error(bank + "-----------getCheckOrder耗时=" + sw.getSplitTime());
		sw.stop();
		logger.error("-----------" + bank + "对单记录总数=" + checkOrders.size());

		try {
			// 继续对账
			String beanName = getSendBankBeanName(bank);
			if (false == SpringContextUtil.containsBean(beanName)) {
				logger.info("spring bean does not exist: " + beanName);
				return;
			}

			BcdlOrderSendBankService sendBankService = (BcdlOrderSendBankService) SpringContextUtil.getBean(beanName);
			HttpTransport notifyGass = new HttpTransport();
			notifyGass.setSendEncoding("UTF-8");
			for (String bankOrderId : sendOrders) {
				BcdlResult result = null;
				BankOrder bankOrder = bisBankOrderQueryDAO.find(BankOrder.class, bankOrderId);
				try {
					// 非生产环境、非一分钱交易直接置为“99”失败
					if (!"prod".equals(bcdlConfig.get("sys.id")) && !"0.01".equals(bankOrder.getSendBankAmt().toString())) {
						bankOrderManager.updateFail(bankOrder);
					} else {
						logger.error("插入发往银行日志--开始 ，orderId="+bankOrder.getOrderId()+",bank="+bank);
		        		bankOrderManager.saveCheckBcdlSendBankLog(bankOrder);
		        		logger.error("插入发往银行日志--结束 ，orderId="+bankOrder.getOrderId()+",bank="+bank);
						logger.error("银企直连 发送银行--开始 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank);
						result = sendBankService.sendBank(bankOrder);
						logger.error("银企直连 发送银行--结束 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank + ",resultCode=" + result.getResultCode());

						Map<String, String> param = new HashMap<String, String>();
						if (ProcCodeConstants.PROC_CODE_100E6027.equals(result.getResultCode())) {
							param.put("resultCode", "2");
							param.put("resultMsg", result.getErrorMsg());
							//delete by zyt,2017-8-4，删除remark标志
							// param.put("remark", "1");
							param.put("gopayOrderId", bankOrder.getOrderId());
							//add by zyt,2017-10-13 ,是否需要做失败的拒绝账务，
							if(result.isNeedRefund()){
								logger.info("发起失败拒绝账务：orderId:" + bankOrder.getOrderId());
								param.put("needRefund", "1");
							}
							/*notifyGass.setUrl(bankOrder.getRemark2());
							notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
							gassPayService.bcdlNotifyGass(param);
						} else if (ProcCodeConstants.PROC_CODE_100S1000.equals(result.getResultCode())) {
							param.put("resultCode", "1");
							//delete by zyt,2017-8-4，删除remark标志
							// param.put("remark", "1");
							param.put("gopayOrderId", bankOrder.getOrderId());
							/*notifyGass.setUrl(bankOrder.getRemark2());
							notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
							gassPayService.bcdlNotifyGass(param);
						} else {
							param.put("resultCode", "3");
							//delete by zyt,2017-8-4，删除remark标志
							// param.put("remark", "1");
							param.put("gopayOrderId", bankOrder.getOrderId());
							/*notifyGass.setUrl(bankOrder.getRemark2());
							notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
							gassPayService.bcdlNotifyGass(param);
						}

						/**
						 * 招商银行，一次请求后暂停2s，中行，一次请求后暂停5s
						 */
						if ("CMB".equalsIgnoreCase(bank)) {
							logger.error("CMB sendbank sleep startTime:" + System.currentTimeMillis());
							sleep(2000);
							logger.error("CMB sendbank sleep endTime:" + System.currentTimeMillis());
						} else if ("BOC".equalsIgnoreCase(bank)) {
							logger.error("BOC sendbank sleep startTime:" + System.currentTimeMillis());
							sleep(5000);
							logger.error("BOC sendbank sleep endTime:" + System.currentTimeMillis());
						}
					}
				} catch (Exception e) {
					logger.error("发送银行异常 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank, e);
				} finally {
					sentinel.patrol(bankOrder, result);
					if (sentinel.isFuse()) {
						logger.error("bcdl_" + bank + ",暂停付款任务");
						break;
					}
				}

			}
			//如果是招行，刚才支付的单子，马上进行一次对账add by sj 20180125
//			if ("CMB".equalsIgnoreCase(bank)) {
//				logger.error("招行银企支付完以后，马上进行对账");
//				checkCMBOrders(bank, sentinel, sendOrders);
//			}
			//System.out.println("==========判断中行整点");
			//如果是中行。每个整点就要将对账次数大于等于15次的订单再跑一次add by sj 20180125
//			if("BOC".equalsIgnoreCase(bank) && isIntePoint()){
//				logger.error("中行银企每个整点就要将对账次数大于等于15次的订单再跑一次");
//				checkBOCOrders(sentinel);
//			}
			
			for (BankOrder bankOrder : checkOrders) {
				CheckOrderResult result = null;
				try {

					// 非生产环境、非一分钱交易直接置为“99”失败
					if (!"prod".equals(bcdlConfig.get("sys.id")) && !"0.01".equals(bankOrder.getSendBankAmt().toString())) {
						bankOrderManager.updateFail(bankOrder);
					} else {

						logger.error("银企直连 对单--开始 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank);
					    result = checkOrder(bankOrder, BankOrderStatus.AUTO_CHECK_SUCCESS);
						logger.error("银企直连 对单--结束 ，orderId=" + bankOrder.getOrderId() + ",ErrCode=" + result.getErrCode() + ",isSuccess=" + result.isSuccess());

						Map<String, String> param = new HashMap<String, String>();
						if (ProcCodeConstants.PROC_CODE_100E6027.equals(result.getErrCode())) {
							param.put("resultCode", "2");
							//delete by zyt,2017-8-4，删除remark标志
							// param.put("remark", "2");
							param.put("resultMsg", result.getErrMsg());
							param.put("gopayOrderId", bankOrder.getOrderId());

							//add by zyt,2017-10-13 ,是否需要做失败的拒绝账务，
							if(result.isNeedRefund()){
								logger.info("发起失败拒绝账务：orderId:" + bankOrder.getOrderId());
								param.put("needRefund", "1");
							}
							/*notifyGass.setUrl(bankOrder.getRemark2());
							notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
							gassPayService.bcdlNotifyGass(param);

						} else if (result.isSuccess()) {
							param.put("resultCode", "1");
							//delete by zyt,2017-8-4，删除remark标志
							// param.put("remark", "2");
							param.put("gopayOrderId", bankOrder.getOrderId());
							/*notifyGass.setUrl(bankOrder.getRemark2());
							notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
							gassPayService.bcdlNotifyGass(param);
						} else {
							param.put("resultCode", "3");
							//delete by zyt,2017-8-4，删除remark标志
							// param.put("remark", "2");
							param.put("gopayOrderId", bankOrder.getOrderId());
							/*notifyGass.setUrl(bankOrder.getRemark2());
							notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
							gassPayService.bcdlNotifyGass(param);
						}

						/**
						 * 招商银行，一次请求后暂停2s，中行，一次请求后暂停5s
						 */
						if ("CMB".equalsIgnoreCase(bank)) {
							logger.error("CMB check sleep startTime:" + System.currentTimeMillis());
							sleep(2000);
							logger.error("CMB check sleep endTime:" + System.currentTimeMillis());
						} else if ("BOC".equalsIgnoreCase(bank)) {
							logger.error("BOC check sleep startTime:" + System.currentTimeMillis());
							sleep(5000);
							logger.error("BOC check sleep endTime:" + System.currentTimeMillis());
						}
					}
				} catch (Exception e) {
					logger.error("对单异常 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank, e);
				} finally {
					sentinel.checkPartol(bankOrder, result);
					if (sentinel.isFuse()) {
						logger.error("bcdl_" + bank + ",暂停付款任务");
						break;
					}
				}

			}

			// 查询账户余额
			List<BcdlQueryBalance> bcdlQuerys = getBcdlQueryOrder(bank);
			if (bcdlQuerys == null || bcdlQuerys.size() <= 0) {
				logger.error("bcdl queryBalance orders is null");
				return;
			}
			BcdlQueryBalance bcdlQuery = bcdlQuerys.get(0);
			logger.error("银企直连 查询余额--开始 ，orderId=" + bcdlQuery.getQueryOrderId() + ",bank=" + bank);
			BcdlResult result = sendBankService.queryBalance(bcdlQuery);
			logger.error("银企直连 查询余额--结束 ，orderId=" + bcdlQuery.getQueryOrderId() + ",ResultCode=" + result.getResultCode() + ",isSuccess=" + result.isSuccess());

			notifyCps(bank, notifyUrl, result);
		} catch (Exception e) {
			logger.error("checkOrder error message: ,bank=" + bank, e);
		}
	}

	public static void main(String[] args) {
		/*Date d = new Date();
		d = DateUtils.strToDate("20180101115911");
		SimpleDateFormat myFmt = new SimpleDateFormat("mm");
		String mm = myFmt.format(d);
		int m = Integer.parseInt(mm);
		System.out.println(m);*/
		
		Calendar calendar = Calendar.getInstance();
		
		//开始时间--最近1天
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, -3);
		String beginTime=DateUtils.format(calendar.getTime(), "yyyyMMdd");
		System.out.println(beginTime);
	}
	
	/**
	 * @Description: 判断当前时间是否是整点
	 * @return 
	 * @author admin
	 */
	private boolean isIntePoint(){
		Date d = new Date();
		SimpleDateFormat myFmt = new SimpleDateFormat("mm");
		String mm = myFmt.format(d);
		int m = Integer.parseInt(mm);
		if(m >= 0 && m < 2){
			return true;
		}else{
			return false;
		}
	}
	
	private void checkCMBOrders(String bank, BcdlOrderSentinel sentinel, List<String> sendOrders) {
		
		//招行发送到银行的订单，立即对账
		for (String bankOrderId : sendOrders) {
			CheckOrderResult result = null;
			BankOrder bankOrder = bisBankOrderQueryDAO.find(BankOrder.class, bankOrderId);
			try {

				result = checkOneOrder(bank, result, bankOrder);
			} catch (Exception e) {
				logger.error("银企对单异常 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank, e);
			} finally {
				sentinel.checkPartol(bankOrder, result);
				if (sentinel.isFuse()) {
					logger.error("bcdl_" + bank + ",暂停付款任务");
					break;
				}
			}

		}
	}
	
	private void checkBOCOrders(BcdlOrderSentinel sentinel){
		List<Object[]> list = getCheckBOCBcdlOrder(BankOrderStatus.PROCESS, 1, MAX_SIZE);
		List<String> orderIds = new ArrayList<String>();
		for (Object[] bankOrderId : list) {
			orderIds.add(StringTools.checkNulltoString(bankOrderId[0]));
		}
		checkCMBOrders("BOC", sentinel, orderIds);
	}

	private CheckOrderResult checkOneOrder(String bank, CheckOrderResult result, BankOrder bankOrder) {
		// 非生产环境、非一分钱交易直接置为“99”失败
		if (!"prod".equals(bcdlConfig.get("sys.id")) && !"0.01".equals(bankOrder.getSendBankAmt().toString())) {
			bankOrderManager.updateFail(bankOrder);
		} else {

			logger.error("银企直连 对单--开始 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank);
		    result = checkOrder(bankOrder, BankOrderStatus.AUTO_CHECK_SUCCESS);
			logger.error("银企直连 对单--结束 ，orderId=" + bankOrder.getOrderId() + ",ErrCode=" + result.getErrCode() + ",isSuccess=" + result.isSuccess());

			Map<String, String> param = new HashMap<String, String>();
			if (ProcCodeConstants.PROC_CODE_100E6027.equals(result.getErrCode())) {
				param.put("resultCode", "2");
				//delete by zyt,2017-8-4，删除remark标志
				// param.put("remark", "2");
				param.put("resultMsg", result.getErrMsg());
				param.put("gopayOrderId", bankOrder.getOrderId());

				//add by zyt,2017-10-13 ,是否需要做失败的拒绝账务，
				if(result.isNeedRefund()){
					logger.info("银企发起失败拒绝账务：orderId:" + bankOrder.getOrderId());
					param.put("needRefund", "1");
				}
				/*notifyGass.setUrl(bankOrder.getRemark2());
				notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
				gassPayService.bcdlNotifyGass(param);

			} else if (result.isSuccess()) {
				param.put("resultCode", "1");
				//delete by zyt,2017-8-4，删除remark标志
				// param.put("remark", "2");
				param.put("gopayOrderId", bankOrder.getOrderId());
				/*notifyGass.setUrl(bankOrder.getRemark2());
				notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
				gassPayService.bcdlNotifyGass(param);
			} else {
				param.put("resultCode", "3");
				//delete by zyt,2017-8-4，删除remark标志
				// param.put("remark", "2");
				param.put("gopayOrderId", bankOrder.getOrderId());
				/*notifyGass.setUrl(bankOrder.getRemark2());
				notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
				gassPayService.bcdlNotifyGass(param);
			}

			/**
			 * 招商银行，一次请求后暂停2s，中行，一次请求后暂停5s
			 */
			if ("CMB".equalsIgnoreCase(bank)) {
				logger.error("CMB check sleep startTime:" + System.currentTimeMillis());
				sleep(2000);
				logger.error("CMB check sleep endTime:" + System.currentTimeMillis());
			} else if ("BOC".equalsIgnoreCase(bank)) {
				logger.error("BOC check sleep startTime:" + System.currentTimeMillis());
				sleep(5000);
				logger.error("BOC check sleep endTime:" + System.currentTimeMillis());
			}
		}
		return result;
	}

    private void sleep(long pausesTime) {
        try {
            Thread.sleep(pausesTime);
        } catch (InterruptedException e) {
            logger.error(getClass().getName() + " CMB doTask fail.", e);
        }
    }
    
    
    

//	public List<BankOrder> getSendBankOrder(String bank) {
//		int count =getOrderCount(BankOrderStatus.ACCEPTED,bank);
//		int pageIndex =1;
//		int pageSize = 0;
//		List<BankOrder> list = new ArrayList<BankOrder>();
//		if(count>MAX_SIZE){
//			pageSize =MAX_SIZE;
//		}else{
//			pageSize = count;
//		}
//		list = getProcessOrder(bank,BankOrderStatus.ACCEPTED, pageIndex, pageSize);
//		return list;
//	}
    
    public List<Object[]> getCheckBcdlOrderByBank(String bank,String orderStatus,int pageIndex, int pageSize){
    	StringBuffer sql = new StringBuffer(250);
    	sql.append("select b.GOPAY_OUT_ORDER_ID,b.GOPAY_ORDER_ID from BIS_BANK_MAIN_ORDER b ");
    	sql.append(" left join checkorder_bcdl_send_bank_log c on b.gopay_order_id = c.gopay_order_id ");
    	sql.append(" where b.ORDER_STATUS = :orderStatus ");
    	sql.append(" and b.BANK_BIZ_PROD_CODE = :bankBizProdCode ");
    	sql.append(" and b.ORDER_TYPE = :orderType ");
    	sql.append(" and b.GOPAY_BANK_CODE = :bankCode ");
        // 获取订单增加渠道码条件
    	sql.append(" and b.INTRFACE_CHANNEL_CODE = :interfaceChennelCode ");
    	sql.append(" and b.TOTAL_CHECK_TIMES <= :totalCheckTimes ");
    	sql.append(" and b.SEND_BANK_TM >=to_date(:beginTime ,'yyyyMMddHH24miss') ");
    	sql.append(" and c.gopay_order_id is null");
    	//修改T+1插队到T+0问题，改成订单号降序
    	//sql.append(" order by b.TOTAL_CHECK_TIMES, b.GOPAY_ORDER_ID desc ");
    	sql.append(" order by b.SEND_BANK_TM asc ");
    	
    	Map<String, Object> params = new HashMap<String, Object>();
    	params.put("orderStatus", orderStatus);
    	params.put("bankBizProdCode", BisBankBusinessProd._09.value);
    	params.put("orderType", BankOrderType.GOPAY_BIS_ORDER);
    	params.put("bankCode", bank);
    	params.put("interfaceChennelCode", BisBankInterfaceChannel._00.value);
    	params.put("totalCheckTimes", 7);

    	params.put("beginTime", recentlyTime());
    	List<Object[]> list = commonQueryDAO.findBySql(sql.toString(), params, pageIndex, pageSize);
    	return list;
    }
    
    
    public List<Object[]> getCheckBOCBcdlOrder(String orderStatus,int pageIndex, int pageSize){
    	StringBuffer sql = new StringBuffer(250);
    	sql.append("select b.GOPAY_OUT_ORDER_ID,b.GOPAY_ORDER_ID from BIS_BANK_MAIN_ORDER b ");
    	sql.append(" where b.ORDER_STATUS = :orderStatus ");
    	sql.append(" and b.BANK_BIZ_PROD_CODE = :bankBizProdCode ");
    	sql.append(" and b.ORDER_TYPE = :orderType ");
    	sql.append(" and b.GOPAY_BANK_CODE = :bankCode ");
    	sql.append(" and b.TOTAL_CHECK_TIMES >= :totalCheckTimes ");
    	sql.append(" and b.SEND_BANK_TM >=to_date(:beginTime ,'yyyyMMddHH24miss') ");
    	//修改T+1插队到T+0问题，改成订单号降序
    	sql.append(" order by b.TOTAL_CHECK_TIMES, b.GOPAY_ORDER_ID desc ");
    	
    	Map<String, Object> params = new HashMap<String, Object>();
    	params.put("orderStatus", orderStatus);
    	params.put("bankBizProdCode", BisBankBusinessProd._09.value);
    	params.put("orderType", BankOrderType.GOPAY_BIS_ORDER);
    	params.put("bankCode", "BOC");
     	params.put("totalCheckTimes", 16);
    	params.put("beginTime", recentlyTime());
    	List<Object[]> list = commonQueryDAO.findBySql(sql.toString(), params, pageIndex, pageSize);
    	return list;
    }
    
    public List<String> getSendBankOrder(String bank) {
		List<Object[]> list = getCheckBcdlOrderByBank(bank,BankOrderStatus.ACCEPTED, 1, MAX_SIZE);
		List<String> orderIds = new ArrayList<String>();
		for (Object[] bankOrderId : list) {
			orderIds.add(StringTools.checkNulltoString(bankOrderId[0]));
		}
		return orderIds;
	}
    
    private String recentlyTime(){
		Calendar calendar = Calendar.getInstance();
		
		//开始时间--最近1天
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, -3);
		String beginTime=DateUtils.format(calendar.getTime(), "yyyyMMddHHmmss");
		
		return beginTime;
	}

	public List<BankOrder> getCheckOrder(String bank, int max) {
		int count =getOrderCount(BankOrderStatus.PROCESS,bank);
		int pageIndex =1;
		int pageSize = 0;
		
		List<BankOrder> list = new ArrayList<BankOrder>();
		if(max<=0){
			return list;
		}
		if(count>max){
			pageSize =max;
		}else{
			pageSize = count;
		}
		list = getProcessOrder(bank,BankOrderStatus.PROCESS, pageIndex, pageSize);
		return list;
	}
	
	private String notifyCps(String bank, String url, BcdlResult result) {
        String notifyUrl = null;
        if (ProcCodeConstants.PROC_CODE_100S1000.equals(result.getResultCode())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            StringBuffer paramters = new StringBuffer();
			StringBuffer paramtersLog = new StringBuffer();
            paramters.append(url).append("?");
            paramters.append("resultCode=").append(ProcCodeConstants.PROC_CODE_100S1000);
            paramters.append("&bankCode=").append(bank);
            paramters.append("&bankAcctAmt=").append((String) result.getModel("balance"));
            paramters.append("&bankName=").append(getBankName(bank));
			paramtersLog.append(paramters);
            paramters.append("&bankCardNo=").append((String) result.getModel("payAccNum"));
            paramters.append("&bankAcctLastUpdTs=").append(sdf.format(new Date()));
			paramtersLog.append("&bankCardNo=").append(LoggerMaskUtils.maskString((String) result.getModel("payAccNum")));
			paramtersLog.append("&bankAcctLastUpdTs=").append(sdf.format(new Date()));
            notifyUrl = paramters.toString();
			logger.error("银企直连 查询余额--通知cps开始 ，响应信息：" + paramtersLog);
		} else {
            StringBuffer paramters = new StringBuffer();
            paramters.append(url).append("?");
            paramters.append("resultCode=").append(ProcCodeConstants.PROC_CODE_100E6027);
            paramters.append("&bankCode=").append(bank);
            notifyUrl = paramters.toString();
			logger.error("银企直连 查询余额--通知cps开始 ，响应信息：" + notifyUrl);
		}

        StringBuffer sb = new StringBuffer();
        try {
            URL hp = new URL(notifyUrl);
            HttpURLConnection conn = (HttpURLConnection) hp.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(false);  
            conn.setDoInput(true);  
            conn.connect();
            boolean isError = conn.getResponseCode() >= 400;
            InputStream is =  isError ? conn.getErrorStream() : conn.getInputStream();
            java.io.BufferedReader in = new BufferedReader(new InputStreamReader(is, "utf-8"));

            String line = "";
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            in.close();
            logger.error("银企直连 查询余额--通知cps结束 ： " + sb.toString());
        } catch (Exception e) {
            logger.error("银企直连 查询余额--通知cps报错: ", e);
            return null;
        }

        return sb.toString();
    }
	
    private String getBankName(String bank) {
        if (bank.equals(BankConstants.BANK_LOGO_ICBC)) {
            return "工商银行";
        } else if (bank.equals(BankConstants.BANK_LOGO_ABC)) {
            return "农业银行";
        } else if (bank.equals(BankConstants.BANK_LOGO_CMB)) {
            return "招商银行";
        } else {
            return null;
        }
    }

	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult = bcdlBankOrderService.checkOrder(bankOrder, target);
		return checkOrderResult;
	}
	
	public List<BcdlQueryBalance> getBcdlQueryOrder(String bank) {
        return bcdlQueryBalanceDAO.getBcdlQueryByBankCodeAndOrderStatus(bank, BankOrderStatus.ACCEPTED);
    }

	private String getSendBankBeanName(String bankCode) throws GopayException {
		String beanName = bankCode + "-BCDL";
		return beanName;
	}

	/*public BankOrderService getBankOrderService() {
		return bankOrderService;
	}

	public void setBankOrderService(BankOrderService bankOrderService) {
		this.bankOrderService = bankOrderService;
	}*/

	public BankOrderService getBcdlBankOrderService() {
		return bcdlBankOrderService;
	}

	public void setBcdlBankOrderService(BankOrderService bcdlBankOrderService) {
		this.bcdlBankOrderService = bcdlBankOrderService;
	}

	/**
     * 分页查询对账记录
     * @param bank
     * @param orderStatus
     * @param pageIndex
     * @param pageSize
     * @return
     */
    private List<BankOrder> getProcessOrder(String bank,String orderStatus, int pageIndex, int pageSize){
    	List<BankOrder> bankOrders = null;
		if (bank.equals(BankConstants.BANK_LOGO_BOC)) {
			logger.error("---checkbcdlbank---boc"+bank);
			bankOrders = bisBankOrderQueryDAO.getCheckBcdlOrderByBanklarge(bank,orderStatus, pageIndex, pageSize);
		}else{
			logger.error("---checkbcdlbank---other"+bank);
			bankOrders = bisBankOrderQueryDAO.getCheckBcdlOrderByBank(bank,orderStatus, pageIndex, pageSize);
		}
		return bankOrders;
    }
    
    private int getOrderCount(String orderStatus,String bank){
    	int resCount = 0;
    	if (bank.equals(BankConstants.BANK_LOGO_BOC)) {
    		resCount = bisBankOrderQueryDAO.getCheckBcdlOrderCountByBankLarge(bank, orderStatus);
    	}else{
    		resCount=bisBankOrderQueryDAO.getCheckBcdlOrderCountByBank(bank, orderStatus);
    	}
        if (resCount > MAX_SIZE) {
            resCount = MAX_SIZE;
        }
        return resCount;
    }
    protected CpsGenMainOrder getMainOrder(String orderId) throws GopayException {
        // 获取主订单表
        CpsGenMainOrder mainOrder = mainOrderQuery.get(orderId);
        if (mainOrder == null) {
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E5041, "mainOrder is null");
        }

        return mainOrder;
    }
	
    
    private void oneTestOrder(String bank, BcdlOrderSentinel sentinel){
		logger.error("bcdl_" + bank + ",执行一分钱测试操作，start");
		
		try {
			String beanName = getSendBankBeanName(bank);
			if (false == SpringContextUtil.containsBean(beanName)) {
				logger.info("spring bean does not exist: " + beanName);
				return;
			}
			BcdlOrderSendBankService sendBankService = (BcdlOrderSendBankService) SpringContextUtil.getBean(beanName);
			//发往银行
			//获取该熔断器下最新的一笔11状态的一分钱测试订单
			BankOrder bankOrder = bankOrderManager.getSendOneTestOrder(sentinel.getSentinelId());
			if(bankOrder != null){
				sendOnFentestOrder(bank, bankOrder, sendBankService);
			}
			
			//对账
			//获取该熔断器下最新的一笔00状态的一分钱测试订单
			BankOrder checkBankOrder = bankOrderManager.getCheckOneTestOrder(sentinel.getSentinelId());
			if(checkBankOrder != null){
				checkOneFenTestOrder(bank, checkBankOrder);
			}
			
		} catch (GopayException e) {
			logger.error("bcdl_" + bank + ",一分钱测试出现异常");
			e.printStackTrace();
		}
		//根据返回的
		logger.error("bcdl_" + bank + ",执行一分钱测试操作，end");
	}

	private void checkOneFenTestOrder(String bank, BankOrder checkBankOrder) {
		logger.error("一分钱测试银企直连 对单--开始 ，orderId=" + checkBankOrder.getOrderId() + ",bank=" + bank);
		CheckOrderResult checkResult = checkOrder(checkBankOrder, BankOrderStatus.AUTO_CHECK_SUCCESS);
		logger.error("一分钱测试银企直连 对单--结束 ，orderId=" + checkBankOrder.getOrderId() + ",ErrCode=" + checkResult.getErrCode() + ",isSuccess=" + checkResult.isSuccess());

		Map<String, String> checkParam = new HashMap<String, String>();
		if (ProcCodeConstants.PROC_CODE_100E6027.equals(checkResult.getErrCode())) {
			checkParam.put("resultCode", "2");
			//delete by zyt,2017-8-4，删除remark标志
			// param.put("remark", "2");
			checkParam.put("resultMsg", checkResult.getErrMsg());
			checkParam.put("gopayOrderId", checkBankOrder.getOrderId());

			//add by zyt,2017-10-13 ,是否需要做失败的拒绝账务，
			if(checkResult.isNeedRefund()){
				logger.info("发起失败拒绝账务：orderId:" + checkBankOrder.getOrderId());
				checkParam.put("needRefund", "1");
			}
			/*notifyGass.setUrl(bankOrder.getRemark2());
			notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
			gassPayService.bcdlNotifyGass(checkParam);

		} else if (checkResult.isSuccess()) {
			checkParam.put("resultCode", "1");
			//delete by zyt,2017-8-4，删除remark标志
			// param.put("remark", "2");
			checkParam.put("gopayOrderId", checkBankOrder.getOrderId());
			/*notifyGass.setUrl(bankOrder.getRemark2());
			notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
			gassPayService.bcdlNotifyGass(checkParam);
		} else {
			checkParam.put("resultCode", "3");
			//delete by zyt,2017-8-4，删除remark标志
			// param.put("remark", "2");
			checkParam.put("gopayOrderId", checkBankOrder.getOrderId());
			/*notifyGass.setUrl(bankOrder.getRemark2());
			notifyGass.submit(param);*/ //生产优化10期 lx httpclient 替换为 hessian
			gassPayService.bcdlNotifyGass(checkParam);
		}
	}

	private void sendOnFentestOrder(String bank, BankOrder bankOrder, BcdlOrderSendBankService sendBankService) {
		logger.error("一分钱测试银企直连 发送银行--开始 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank);
		BcdlResult result = sendBankService.sendBank(bankOrder);
		logger.error("一分钱测试银企直连 发送银行--结束 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank + ",resultCode=" + result.getResultCode());
		Map<String, String> param = new HashMap<String, String>();
		if (ProcCodeConstants.PROC_CODE_100E6027.equals(result.getResultCode())) {
			param.put("resultCode", "2");
			param.put("resultMsg", result.getErrorMsg());
			param.put("gopayOrderId", bankOrder.getOrderId());
			if(result.isNeedRefund()){
				logger.info("发起失败拒绝账务：orderId:" + bankOrder.getOrderId());
				param.put("needRefund", "1");
			}
			gassPayService.bcdlNotifyGass(param);
		} else if (ProcCodeConstants.PROC_CODE_100S1000.equals(result.getResultCode())) {
			param.put("resultCode", "1");
			param.put("gopayOrderId", bankOrder.getOrderId());
			gassPayService.bcdlNotifyGass(param);
		} else {
			param.put("resultCode", "3");
			param.put("gopayOrderId", bankOrder.getOrderId());
			gassPayService.bcdlNotifyGass(param);
		}
	}
    


	public CpsGeneralMainOrderQueryManager getMainOrderQuery() {
		return mainOrderQuery;
	}

	public void setMainOrderQuery(CpsGeneralMainOrderQueryManager mainOrderQuery) {
		this.mainOrderQuery = mainOrderQuery;
	}

	public BankOrderManager getBankOrderManager() {
		return bankOrderManager;
	}

	public void setBankOrderManager(BankOrderManager bankOrderManager) {
		this.bankOrderManager = bankOrderManager;
	}

    @Override
    public void processNucc(String bankCode, String notifyUrl) {
        // TODO Auto-generated method stub
        
    }
}
